#!/bin/bash
export PATH="/usr/bin:/usr/sbin:${PATH}"
set -euo pipefail

# Generators don't have logging right now
# https://github.com/systemd/systemd/issues/15638
exec 1>/dev/kmsg; exec 2>&1

UNIT_DIR="${1:-/tmp}"

# Turn out if you boot with "root=..." $UNIT_DIR is not writable.
[ -w "${UNIT_DIR}" ] || {
    echo "skipping coreos-boot-mount-generator: ${UNIT_DIR} is not writable"
    exit 0
}

add_wants() {
    local name="$1"; shift
    local wants_dir="${UNIT_DIR}/local-fs.target.wants"
    mkdir -p "${wants_dir}"
    ln -sf "../${name}" "${wants_dir}/${name}"
}

# If there's already an /etc/fstab entries for /boot, then this is is a non-FCOS
# system, likely RHCOS pre-4.3 (which still used Anaconda).  In that case, we
# don't want to overwrite what the systemd-fstab-generator will do.
if findmnt --fstab /boot &>/dev/null; then
    exit 0
fi

# Generate mount units that work with device mapper. The traditional
# device unit (dev-disk-by\x2dlabel...) does not work since it is not the
# device that systemd will fsck. This code ensures that if the label
# is backed by a device-mapper target the dev-mapper.*.device is used.
mk_mount() {
    local unit_name="${1}.mount"; shift
    local label="${1}"; shift
    local mount_pt="${1:-/$label}"
    local path="/dev/disk/by-label/${label}"

    eval $(udevadm info --query property --export "${path}")
    device="$(systemd-escape ${path})"
    if [ "${DM_NAME:-x}" != "x" ]; then
        path="/dev/mapper/${DM_NAME}"
        device="$(systemd-escape dev/mapper/${DM_NAME})"
    fi
    device="${device//-dev/dev}"
    echo "coreos-boot-mount-generator: using ${device} for ${label} mount to ${mount_pt}"

    cat > "${UNIT_DIR}/${unit_name}" <<EOF
# Automatically created by coreos-boot-mount-generator
[Unit]
Description=CoreOS Dynamic Mount for ${mount_pt}
Documentation=https://github.com/coreos/fedora-coreos-config

Before=local-fs.target
Requires=systemd-fsck@${device}.service
After=systemd-fsck@${device}.service

[Mount]
What=${path}
Where=${mount_pt}
EOF

    add_wants "${unit_name}"
}


# Don't create mount units for /boot or /boot/efi on live systems.
# ConditionPathExists won't work here because conditions don't affect
# the dependency on the underlying device unit.
if [ ! -f /run/ostree-live ]; then
    mk_mount boot boot

    # Only mount the EFI System Partition on machines where it exists,
    # which are 1) machines actually booted through EFI, and 2) x86_64
    # when booted through BIOS.
    if [ "$(uname -m)" = "x86_64" -o -d /sys/firmware/efi ]; then
        mk_mount boot-efi EFI-SYSTEM "/boot/efi"
    fi
fi
